<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\middleware\base_supplier\ActiveSupplierMiddleware;
use app\model\BaseSupplier as Model;
use think\Request;
use think\facade\Db;

class BaseSupplier extends Controller
{

    protected $middleware = [
        ActiveSupplierMiddleware::class => ['only' => 'save'],
    ];

    /**
     * @api {GET} /admin/baseSupplier/ 供应商列表
     * @apiName 供应商列表
     * @apiDescription 供应商列表
     * @apiGroup Admin2_0
     * @apiParam {Number} type 类型 [1 => '话费', 2 => '加油', 3 => '权益', 4 => '外卖', 5 => '影票']
     * @apiParam {String} [name] 供应商名
     * @apiParam {Number} [page] 页码
     * @apiParam {Number} [list_rows] 页面大小
     *
     * @apiUse PageReturn
     * @apiVersion 1.0.0
     */
    public function index(Request $request)
    {
        if (!request()->has('serv_type')) {
            return fail('非法类型');
        }
        $serv_type = $request->param('serv_type');

        if ($serv_type == -10) {
            $where = [
                ['serv_type', 'in', [PRODUCT_SECKILL_SERV, PRODUCT_METUAN_SERV]],
            ];
        } elseif ($serv_type == 'takeout') {
            //外卖
            $where = [
                ['type', '=', 'takeout'],
            ];
        } else {
            $where = [
                ['serv_type', '=', $request->param('serv_type')],
            ];

        }


        if ($name = $request->param('name')) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $list = Model::where($where)
            ->order('id desc')
            ->withCount("couponProducts")
            ->paginate($this->getPaginate())
            ->toArray();
        if ($list['data']) {
            $supplierIds = array_column($list['data'], 'id');
            $rechargeSupplierConfig = \think\facade\Db::name('recharge_supplier_config')
                ->whereIn('supplier_id', $supplierIds)
                ->column('fast_settle_value, fast_priority,
                slow_settle_value, slow_priority', 'supplier_id');
            $servType = $request->param('serv_type');
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['charge_config'] = $rechargeSupplierConfig[$v['id']] ?? [];

                // 权益商品，统计下各个供应商对接商品数
                if ($servType === PRODUCT_COUPON_SERV) {
//                    $list['data'][$k]['goods_count'] = Db::name('coupon_goods')
//                        ->where('supplier_id', $v['id'])
//                        ->where('relate_state', 1)
//                        ->whereNull('deleted_at')
//                        ->count();
                    $list['data'][$k]['goods_count'] = $v['coupon_products_count'];
                }
            }
        }

        return success('操作成功', $list);
    }

    /**
     * @api {POST} /admin/baseSupplier/save 供应商新建或者保存
     * @apiName aupplierSave 供应商新建或者保存
     * @apiGroup Admin2_0
     * @apiParam {Number} [id] id 更新时候传递
     * @apiParam {String} name 名称
     * @apiParam {String} code 别名
     * @apiParam {Number} gate_rate 通道费用
     * @apiParam {String} settle_type 结算方式
     * @apiParam {String} settle_value 结算折扣或返佣比例
     * @apiParam {String} [api_config[key]] 配置
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function save(Request $request)
    {
        // 充值相关类型的
        if (in_array($request->param('serv_type'), [PRODUCT_OILCARD_SERV, PRODUCT_POWER_SERV])) {
            return $this->chargeSave($request);
        }

        $rules = [
            'name' => 'require',
            'code' => 'require',
//            'settle_type' => 'require',
//            'settle_value' => 'require|float',
            // 'gate_rate' => 'require|float',
            //'config' => 'require',
        ];
        $messages = [
            'name.require' => '请输入名称',
            'code.require' => '请输入代号',
            'float' => '输入数字格式',
            'require' => '缺少必要参数',
            //'config.require' => '请',
        ];
        $param = $request->only(['name',
            'code', 'api_config' => '',
            'settle_type', 'settle_value', 'gate_rate','type']);

        $id = $request->param('id', 0);
        if (!$id) {
            if (!$request->has('serv_type')) {
                return fail('非法参数');
            }
            $param['serv_type'] = $request->param('serv_type');
        }
        $param['serv_type'] = $request->param('serv_type');

        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }
        if (mb_strlen(json_encode($param['api_config'])) > 255) {
            return fail('配置项多，请不要配置无用东西，或者联系技术');
        }

        if ($id) {
            $supplier = Model::find($id);
            $existData = Model::where('id', '<>', $id)->where('serv_type', $supplier->serv_type)->where(function ($query) use ($param) {
                $query->where('name', '=', $param['name'])->whereOr('code', '=', $param['code']);
            })->find();
        } else {
            $supplier = new Model();
            $existData = Model::where('serv_type', $param['serv_type'])->where(function ($query) use ($param) {
                $query->where('name', '=', $param['name'])->whereOr('code', '=', $param['code']);
            })->find();
        }

        // 名称校验
        if ($existData) {
            return fail('名称或者代号和id=' . $existData['id'] . '的冲突了');
        }

        if ($supplier->save($param)) {
            return success();
        } else {
            return fail();
        }
    }

    /**
     * @api {POST} /admin/baseSupplier/chargeSave 充值类型供应商新建或者保存
     * @apiName chargeSupplierSave 充值类型供应商新建或者保存
     * @apiGroup Admin2_0
     * @apiParam {Number} [id] id 更新时候传递
     * @apiParam {String} name 名称
     * @apiParam {String} code 别名
     * @apiParam {Number} gate_rate 通道费用
     * @apiParam {Array} charge_config[]  充值相关配置  [fast_state,fast_priority,fast_settle_value,slow+和fast_相关]
     * @apiParam {String} [api_config[key]] 运用配置
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function chargeSave(Request $request)
    {
        $rules = [
            'name' => 'require',
            'code' => 'require',
            'charge_config' => 'require|array',
            // 'gate_rate' => 'require|float',
            //'config' => 'require',
        ];
        $messages = [
            'name.require' => '请输入名称',
            'code.require' => '请输入代号',
            'float' => '输入数字格式',
            'require' => '缺少必要参数',
            'charge_config.require' => '请填写快慢充配置',
            'charge_config.array' => '请填写快慢充配置',
            //'config.require' => '请',
        ];
        $param = $request->only(['name', 'code', 'api_config' => '', 'charge_config', 'gate_rate']);
        // 充值类型 先默认 结算预充
        $param['settle_type'] = 1;

        // todo 对serv_type 做限制

        $id = $request->param('id', 0);
        if (!$id) {
            if (!$request->has('serv_type')) {
                return fail('非法参数');
            }
            $param['serv_type'] = $request->param('serv_type');
        }
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }

        if (mb_strlen(json_encode($param['api_config'])) > 255) {
            return fail('配置项多，请不要配置无用东西，或者联系技术');
        }

        if ($id) {
            $model = Model::with('rechargeConfig')->find($id);
            $existData = Model::where('id', '<>', $id)->where('serv_type', $model->serv_type)->where(function ($query) use ($param) {
                $query->where('name', '=', $param['name'])->whereOr('code', '=', $param['code']);
            })->find();
        } else {
            $model = new Model();
            $existData = Model::where('serv_type', $param['serv_type'])->where(function ($query) use ($param) {
                $query->where('name', '=', $param['name'])->whereOr('code', '=', $param['code']);
            })->find();
        }

        // 名称校验
        if ($existData) {
            return fail('名称或者代号和id=' . $existData['id'] . '的冲突了');
        }

        //  处理 充值配置
        $rechargeConfig = $param['charge_config'];
        if ('string' == gettype($rechargeConfig)) {
            $rechargeConfig = json_decode($rechargeConfig, true);
        }
        $rechargeConfig['fast_state'] = $rechargeConfig['fast_state'] ?? 1;
        $rechargeConfig['slow_state'] = $rechargeConfig['slow_state'] ?? 1;
        unset($param['charge_config']);
        if ($model->rechargeConfig) {
            $rechargeConfig['id'] = $model->rechargeConfig->id;
        }

        // 执行保存
        if ($model->save($param)) {
            if ($model->rechargeConfig()->save($rechargeConfig)) {
                return success();
            } else {
                return fail();
            }
        } else {
            return fail();
        }
    }

    /**
     * @api {POST} /admin/baseSupplier/delete 供应商删除
     * @apiName 供应商删除
     * @apiGroup Admin2_0
     * @apiParam {Number} id id
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function delete(Request $request)
    {
        if (!$id = $request->param('id', 0)) {
            return fail('缺少必要参数');
        }
        if (Model::destroy($id)) {
            return success();
        }

        return fail();
    }

    /**
     * 获取供应商最新账户余额
     */
    public function getBalance(Request $request)
    {
        $data = input('post.');
        if (empty($data['id'])) {
            return fail('id 不能为空');
        }
        if (empty($data['type'])) {
            return fail('类型有误');
        }

        return Model::getBalance($data['id'], $data['type']);
    }
}
